'use strict';

var gulp = require('gulp'),
    minifycss = require('gulp-minify-css'),//gulp压缩css插件  npm install gulp-minify-css --save-dev 插件已更新为gulp-clean-css可选择更换
    htmlmin = require('gulp-htmlmin'),//压缩html
    imagemin = require('gulp-imagemin'),//压缩images
    templateCache = require('gulp-angular-templatecache'),
    concat = require('gulp-concat'),//gulp合并文件插件  npm install gulp-concat --save-dev
    uglify = require('gulp-uglify'),//gulp压缩js插件  npm install gulp-uglify --save-dev
    rename = require('gulp-rename'),//gulp重命名插件  npm install gulp-rename --save-dev
    del = require('del'),//gulp清空构建目录插件  npm install del --save-dev
    runSequence = require('run-sequence'),//处理任务队列
    browserSync = require('browser-sync'),//浏览器实时、快速响应文件(html、js、css、sass、less等等)的更改
    changed = require('gulp-changed'),//只编译改动过的文件,减少重复编译  npm install gulp-changed -save-dev
    rev = require('gulp-rev'),//自动添加版本号unicorn.css => unicorn-d41d8cd98f.css
    inject = require('gulp-inject'),//自动插入静态文件到html
    plumber = require('gulp-plumber'),//处理所有错误的通用方法
    naturalSort = require('gulp-natural-sort'),//按路径名称排序
    angularFilesort = require('gulp-angular-filesort'),//AngularJs
    bowerFiles = require('main-bower-files'),
    flatten = require('gulp-flatten'),
    ngConstant = require('gulp-ng-constant'),//用于动态的生成angular模板
    eslint = require('gulp-eslint'),
    gulpIf = require('gulp-if'),//用来gulp判断
    es = require('event-stream');//用于简化streams调用的api


//获取gulp目录下的公共配置
var config = require('./gulp/config');
var handleErrors = require('./gulp/handleErrors'),
    util = require('./gulp/utils'),
    build = require('./gulp/build');

//清空前端构建缓存
gulp.task('clean',function(){
   return del([config.dist],{dot:true});
});

gulp.task('copy',function(){
    return es.merge(
        /*gulp.src(config.app+'i18n/!**')
            .pipe(plumber({errorHandler:handleErrors}))
            .pipe(changed(config.dist+'i18n/'))
            .pipe(gulp.dest(config.dist+'i18n/')),*/
        gulp.src(config.bower+'bootstrap-css-only/fonts/*.*')
            .pipe(plumber({errorHandle: handleErrors}))
            .pipe(changed(config.dist+'content/fonts/'))
            .pipe(rev())
            .pipe(gulp.dest(config.dist+'content/fonts/'))
            .pipe(rev.manifest(config.revManifest,{
                base: config.dist,
                merge: true
            }))
            .pipe(gulp.dest(config.dist)),
        gulp.src(config.app+'content/**/*.{woff,woff2,svg,ttf,eot,otf}')
            .pipe(plumber({errorHandle:handleErrors}))
            .pipe(changed(config.dist+'content/fonts'))
            .pipe(flatten())
            .pipe(rev())
            .pipe(gulp.dest(config.dist+'content/fonts'))
            .pipe(rev.manifest(config.revManifest,{
                base:config.dist,
                merge:true
            }))
            .pipe(gulp.dest(config.dist))
    );
});

gulp.task('images', function () {
    //如果有图片，这里添加上图片的gulp处理
    return gulp.src(config.app + 'content/images/**')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/images'))
        .pipe(imagemin({optimizationLevel: 5, progressive: true, interlaced: true}))
        .pipe(rev())
        .pipe(gulp.dest(config.dist+'content/images'))
        .pipe(rev.manifest(config.revManifest,{
            base: config.dist,
            marge: true
        }))
        .pipe(gulp.dest(config.dist))
        .pipe(browserSync.reload({stream: true}));
});

gulp.task('languages', function () {
    //如果有国际化i18n，这里添加上国际化i18n的gulp处理
});

gulp.task('styles',[], function () {
    //这里可以增加样式处理
    return gulp.src(config.app + 'content/css')
        .pipe(browserSync.reload({stream: true}));
});

gulp.task('html',[], function () {
    return gulp.src(config.app + 'app/**/*.html')
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(templateCache({
            module: 'myApp',
            root: 'app/',
            moduleSystem: 'IIFE'
        }))
        .pipe(gulp.dest(config.tmp));
});

//合并上面的几个任务
gulp.task('assets:prod', ['images', 'styles', 'html'],build);


gulp.task('inject:app', function () {
    return gulp.src(config.app + 'index.html')
        .pipe(inject(gulp.src(config.app + 'app/**/*.js')
            .pipe(naturalSort())
            .pipe(angularFilesort()),{relative: true}))
        .pipe(gulp.dest(config.app));
});

gulp.task('inject:vendor', function () {
    return gulp.src(config.app + 'index.html')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(inject(gulp.src(bowerFiles(),{read: false}),{
            name: 'bower',
            relative: true
        }))
        .pipe(gulp.dest(config.app));
});

gulp.task('inject:test', function () {
    //可补充karma测试
});

gulp.task('inject',['inject:dep','inject:app']);
gulp.task('inject:dep',['inject:test','inject:vendor']);


gulp.task('inject:troubleshoot', function () {
    //此任务从index.html删除'<!-- inject:troubleshoot -->开始部分内容
    return gulp.src(config.app+'index.html')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(inject(gulp.src('',{read: false}),{
            starttag: '<!-- inject:troubleshoot -->',
            removeTags: true,
            transform: function () {
                return '<!-- Angular views -->';
            }
        }))
        .pipe(gulp.dest(config.app));
});

//开发环境
gulp.task('ngconstant:dev', function () {
   return ngConstant({
       name: 'myApp',
       constants: {
           VERSION:util.parseVersion(),
           DEBUG_INFO_ENABLED:true
       },
       template:config.constantTemplate,
       stream:true
   })
       .pipe(rename('app.constants.js'))
       .pipe(gulp.dest(config.app+'app/'));
});


//生产环境
gulp.task('ngconstant:prod', function () {
    return ngConstant({
        name: 'myApp',
        constants:{
            VERSION: util.parseVersion(),
            DEBUG_INFO_ENABLED: false
        },
        template:config.constantTemplate,
        stream:true
    })
        .pipe(rename('app.constants.js'))
        .pipe(gulp.dest(config.app+'app/'));
});

gulp.task('test',['inject:test','ngconstant:dev'], function () {
    //可增加Karma测试
});

//检查应用程序的ESLint错误
gulp.task('eslint', function () {
   return gulp.src(['gulpfile.js',config.app+'app/**/*.js'])
       .pipe(plumber({errorHandler: handleErrors}))
       .pipe(eslint())
       .pipe(eslint.format())
       .pipe(eslint.failOnError());
});

gulp.task('eslint:fix', function () {
   return gulp.src(config.app+'app/**/*.js')
       .pipe(plumber({errorHandler:handleErrors}))
       .pipe(eslint({
           fix:true
       }))
       .pipe(eslint.format())
       .pipe(gulpIf(util.isLintFixed,gulp.dest(config.app+'app')));
});

gulp.task('watch', function () {
    gulp.watch('bower.json',['install']);
    gulp.watch(['gulpfile.js','build.gradle'],['ngconstant:dev']);
    gulp.watch(config.app+'content/css/**/*.css',['styles']);
    gulp.watch(config.app+'content/images/**',['images']);
    gulp.watch(config.app+'app/**/*.js',['inject:app']);
    gulp.watch([config.app+'*.html',config.app+'app/**',config.app+'i18n/**']).on('change',browserSync.reload);
});

gulp.task('install', function () {
    runSequence(['inject:dep','ngconstant:dev','languages','inject:app','inject:troubleshoot']);
});

gulp.task('serve', function () {
   //runSequence('install',serve);
});

gulp.task('build',['clean'], function (cb) {
    runSequence(['copy','inject:vendor','ngconstant:prod','languages'],'inject:app','inject:troubleshoot','assets:prod',cb);
})

//默认命令，在cmd中输入gulp后，执行的就是这个命令
gulp.task('default',['serve']);
